package org.cfx.auth.service.impl;

import lombok.Data;
import org.cfx.auth.domain.AuthPermission;
import org.cfx.auth.domain.AuthRole;
import org.cfx.auth.domain.AuthRolePermission;
import org.cfx.auth.domain.dto.RoleDto;
import org.cfx.auth.mapper.AuthRolePermissionMapper;
import org.cfx.auth.service.IAuthRoleService;
import org.cfx.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author cfx
 * @since 2023-09-12
 */
@Service
public class AuthRoleServiceImpl extends BaseServiceImpl<AuthRole> implements IAuthRoleService {

    @Autowired
    private AuthRolePermissionMapper authRolePermissionMapper;

    @Override
    @Transactional
    public void saveRoleAndPermission(RoleDto roleDto) {
        AuthRole role = roleDto.getRole();
        super.add(role);

        List<AuthRolePermission> permissions = rolePermissions(roleDto, role.getId());

        authRolePermissionMapper.batchSave(permissions);
    }

    @Override
    public List<Long> loadPermissionByRoleId(Long id) {
        return authRolePermissionMapper.loadPermissionByRoleId(id);
    }

    @Override
    public void updateRoleAndPermission(RoleDto roleDto) {
        //1、更新角色数据
        super.update(roleDto.getRole());
        //2、更新角色与中间资源表
        //  2.1、清空表
        authRolePermissionMapper.removeByRoleId(roleDto.getRole().getId());
        // 2.2、重新写入新的数据
        List<AuthRolePermission> permissions = rolePermissions(roleDto, roleDto.getRole().getId());

        authRolePermissionMapper.batchSave(permissions);

    }
    private List<AuthRolePermission> rolePermissions(RoleDto roleDto,Long roleId) {
        List<AuthRolePermission> permissions = new ArrayList<>();
        for (AuthPermission permission : roleDto.getPermissions()) {
            AuthRolePermission authRolePermission = new AuthRolePermission();
            authRolePermission.setRoleId(roleId);
            authRolePermission.setPermissionId(permission.getId());
            authRolePermission.setPermissionSn(permission.getSn());
            permissions.add(authRolePermission);
        }
        return permissions;
    }

}
